package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.AgriculturalForumTopicAnswerListAdapter;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseSingleChoiceDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.common.SimpleResponse;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CompanyForumAnswer;
import com.isunland.managesystem.entity.CompanyForumTopic;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.CustomTextView;
import com.isunland.managesystem.widget.RoundImageView;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/16 15:29
 */
public class AgriculturalForumDetailFragment extends BaseListFragment
    implements View.OnClickListener {

  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.AgriculturalForumDetailFragment.EXTRA_VALUE";
  //帖子列表来源
  public static final String EXTRA_FROM =
      "com.isunland.managesystem.ui.AgriculturalForumDetailFragment.EXTRA_FROM";
  public static final int RESULT_EDIT = 6;
  protected static final String TAG = "CompanyForumTopicAnswerListFragment";
  private static final int REQUEST_CHOOSE = 0;
  private static final int REQUEST_REPLY = 0; // 话题回复
  private static final int REQUEST_MESSAGE = 1;//查看资料
  private static final int REQUEST_DELETE = 2;//删除回复
  private static final int REQUEST_ADOPT = 3;//采纳回复

  private static final int REQUEST_TOPIC_ANSWER = 2; // 话题的回复
  private static final int REQUEST_TOPIC_ANSWER_REPLY = 3;// 对应目标数据的回复
  private static final int MENU_ITEM_TAG = 6;
  private static final int REQUEST_TAG = 7;
  private static final String[][] MIME_MapTable = {
      // {后缀名，MIME类型}
      { ".3gp", "video/3gpp" }, { ".apk", "application/vnd.android.package-archive" },
      { ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" },
      { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" }, { ".c", "text/plain" },
      { ".class", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" },
      { ".doc", "application/msword" },
      { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
      { ".xls", "application/vnd.ms-excel" },
      { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
      { ".exe", "application/octet-stream" }, { ".gif", "image/gif" },
      { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" },
      { ".htm", "text/html" }, { ".html", "text/html" }, { ".jar", "application/java-archive" },
      { ".java", "text/plain" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" },
      { ".js", "application/x-javascript" }, { ".log", "text/plain" },
      { ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" },
      { ".m4p", "audio/mp4a-latm" }, { ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" },
      { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" },
      { ".mp4", "video/mp4" }, { ".mpc", "application/vnd.mpohun.certificate" },
      { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" },
      { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".msg", "application/vnd.ms-outlook" },
      { ".ogg", "audio/ogg" }, { ".pdf", "application/pdf" }, { ".png", "image/png" },
      { ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" },
      { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
      { ".prop", "text/plain" }, { ".rc", "text/plain" }, { ".rmvb", "audio/x-pn-realaudio" },
      { ".rtf", "application/rtf" }, { ".sh", "text/plain" }, { ".tar", "application/x-tar" },
      { ".tgz", "application/x-compressed" }, { ".txt", "text/plain" }, { ".wav", "audio/x-wav" },
      { ".wma", "audio/x-ms-wma" }, { ".wmv", "audio/x-ms-wmv" },
      { ".wps", "application/vnd.ms-works" }, { ".xml", "text/plain" },
      { ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, { "", "*/*" }
  };

  public ImageView ivPictureAFourmDetail;// 图片A
  public ImageView ivPictureBFourmDetail;// 图片B
  public ImageView ivPictureCFourmDetail;// 图片C
  public ImageView ivPictureDFourmDetail;// 图片D
  public ImageView ivPictureEFourmDetail;// 图片E
  public ImageView ivPictureFFourmDetail;// 图片F
  public TextView tvFileForumDetail; // 文件
  //public LinearLayout llBg;

  private AgriculturalForumTopicAnswerListAdapter mAdapter;
  private CompanyForumTopic.actualObject mTopicContent;
  private CompanyForumAnswer.actualObject mTopicAnswer;
  private String mTopicPublisher;
  private String mTopicTitle;
  private String mTopicdetail;
  private String mTopicPublishTime;
  private String mTopicConmmentNum;
  private String mPictureA;
  private String mPictureB;
  private String mPictureC;
  private String mPictureD;
  private String mPictureE;
  private String mPictureF;
  private String mFile;
  private String mId; // 话题的id
  private String mPicture;// 头像
  private ImageLoader mImageLoader;

  private String mTopicPublisherId;// 话题发布人ID
  private String mJobNu;// 当前登录人的ID
  private String mTopicId;// 话题ID
  private String mAnseerTopicId;// 话题回复消息ID
  private String mPublishJobNo;//发布人的jobNo。
  private String mReplyJobNo;//回复人jobNO

  private String mFrom;
  private CustomTextView ivTag;
  private ArrayList<String> pics = new ArrayList<>();

  public static Fragment newInstance(CompanyForumTopic.actualObject topicContent, String from) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, topicContent);
    bundle.putString(EXTRA_FROM, from);
    AgriculturalForumDetailFragment framgnet = new AgriculturalForumDetailFragment();
    framgnet.setArguments(bundle);
    return framgnet;
  }

  @SuppressWarnings("unused") @SuppressLint("DefaultLocale")
  private static String getMIMEType(File file) {

    String type = "*/*";
    String fName = file.getName();
    // 获取后缀名前的分隔符"."在fName中的位置。
    int dotIndex = fName.lastIndexOf(".");
    if (dotIndex < 0) {
      return type;
    }
        /* 获取文件的后缀名 */
    String end = fName.substring(dotIndex, fName.length()).toLowerCase();
    if (TextUtils.isEmpty(end)) return type;
    // 在MIME和文件类型的匹配表中找到对应的MIME类型。
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < MIME_MapTable.length; i++) {
      if (end.equals(MIME_MapTable[i][0])) type = MIME_MapTable[i][1];
    }
    return type;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.topic);
  }

  /**
   * 添加回复、删除按钮
   */
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_forum_agricultural, menu);
    //具体分类,收藏的分类: 可以收藏帖子
    //if (!AgriculturalForumListFragment.TYPE.equalsIgnoreCase(mFrom)||!AgriculturalForumListFragment.COLLECT_TYPE.equalsIgnoreCase(mFrom)) {
    //  menu.getItem(2).setVisible(false);
    //}

    if (AgriculturalForumListFragment.SELF.equalsIgnoreCase(mFrom)
        || AgriculturalForumListFragment.COLLECT.equalsIgnoreCase(mFrom)) {
      menu.getItem(2).setVisible(false);
    }

    //发布的帖子: 允许删除
    if (!AgriculturalForumListFragment.SELF.equalsIgnoreCase(mFrom)) {
      menu.getItem(1).setVisible(false);
    }
    //收藏的帖子: 允许取消收藏
    if (!AgriculturalForumListFragment.COLLECT.equalsIgnoreCase(mFrom)) {
      menu.getItem(3).setVisible(false);
    }
    //当前登录人和记录提醒的专家相同时才能打标签
    if (MyStringUtil.equals(mCurrentUser.getJobNumber(), mTopicContent.getRemindJobNo())) {
      menu.add(0, MENU_ITEM_TAG, 0, "颜色标签");
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  /**
   * 响应ActionBar中的按钮
   */
  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      // 响应返回按钮

      case android.R.id.home:
        getActivity().finish();
        return true;

      // 响应回复按钮
      case R.id.menu_item_turn_reply:
        Intent intent = new Intent(getActivity(), KnowledgeFroumTopicReplyActivity.class);
        intent.putExtra(KnowledgeFroumTopicReplyFragment.EXTRA_ID, mId);
        intent.putExtra(KnowledgeFroumTopicReplyFragment.REQUEST_TYPE,
            KnowledgeFroumTopicReplyFragment.VALUE_TIPIC_REPLY);
        startActivityForResult(intent, REQUEST_TOPIC_ANSWER);
        return true;

      //打标签
      case MENU_ITEM_TAG:
        showDialog(ColorTagDialogFragment.newInstance(
            new BaseParams().setCode(mTopicContent.getTopicKindCode())
                .setName(mTopicContent.getTopicKindName()), new ColorTagDialogFragment()),
            REQUEST_TAG);
        return true;

      // 删除话题
      case R.id.menu_item_delete_topic:

        if (mPublishJobNo.equalsIgnoreCase(mJobNu)) {
          volleyDeleteTopic();
        } else {
          Toast.makeText(getActivity(), R.string.onlyPublisherDelete, Toast.LENGTH_SHORT).show();
        }
        return true;
      // 收藏帖子
      case R.id.menu_item_collect:
        volleyPostCollect();
        return true;

      // 取消收藏帖子
      case R.id.menu_item_cancle:
        volleyPostCancleCollect();
        return true;

      // 分享帖子
      case R.id.menu_item_share:
        volleyPostShare();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public void initData() {
    super.initData();
    mTopicContent = (CompanyForumTopic.actualObject) getArguments().getSerializable(EXTRA_VALUE);
    if (mTopicContent == null) mTopicContent = new CompanyForumTopic().new actualObject();
    mFrom = getArguments().getString(EXTRA_FROM);
    if (mTopicContent != null) {
      mTopicPublisher = mTopicContent.getRegStaffName();
      mTopicTitle = mTopicContent.getTopicTitle();
      mTopicdetail = mTopicContent.getTopicContents();
      mTopicPublishTime = mTopicContent.getRegDate();
      mTopicConmmentNum = mTopicContent.getDiscussCount();
      mId = mTopicContent.getId();
      mPicture = mTopicContent.getPicture();
      mPictureA = mTopicContent.getTopicPicA();
      mPictureB = mTopicContent.getTopicPicB();
      mPictureC = mTopicContent.getTopicPicC();
      mPictureD = mTopicContent.getTopicPicD();
      mPictureE = mTopicContent.getTopicPicE();
      mPictureF = mTopicContent.getTopicPicF();
      mFile = mTopicContent.getTopicFile();
      mTopicPublisherId = mTopicContent.getRegStaffId();
      mTopicId = mTopicContent.getId();
    }
    CurrentUser mCurrentUser = CurrentUser.newInstance(getActivity());
    mImageLoader = RequestManager.getImageLoader();
    mJobNu = mCurrentUser.getJobNumber();

    mPublishJobNo = mTopicPublisherId;
    if ((null != mTopicPublisherId) && mTopicPublisherId.contains("+")) {
      String[] resultArray = mTopicPublisherId.split("\\+");
      if (resultArray.length > 0) {
        //获取jobNO。
        mPublishJobNo = resultArray[0];
      }
    }
  }

  @Override public String getUrl() {

    return ApiConst.URL_KNOWLEDGEFORUM_REPLY_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("app", "app");
    params.put("mainId", mId);
    params.put("orderField", "REG_DATE");
    params.put("orderSeq", "DESC");
    return params.getParams();
  }

  @Override protected String setEmptyText() {
    return getResources().getString(R.string.noMessageReply);
  }

  @Override public void resolveResponse(String arg0) {
    CompanyForumAnswer answer = new Gson().fromJson(arg0, CompanyForumAnswer.class);
    List<CompanyForumAnswer.actualObject> answerDetail = answer.getData();
    setAdapter(answerDetail);
  }

  private void setAdapter(List<CompanyForumAnswer.actualObject> answerDetail) {
    if (answerDetail == null) {
      answerDetail = new ArrayList<>();
    }
    if (mAdapter == null) {
      mAdapter = new AgriculturalForumTopicAnswerListAdapter(getActivity(), answerDetail, mFrom);
      setListAdapter(mAdapter);
      return;
    }
    mAdapter.clear();
    mAdapter.addAll(answerDetail);
    ((AgriculturalForumTopicAnswerListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_forum_topic_header, null,
            false);
    mListview.addHeaderView(header);

    RoundImageView mImageForumAnswer =
        (RoundImageView) header.findViewById(R.id.iv_image_forum_answer);
    TextView mNameForumAnswer = (TextView) header.findViewById(R.id.tv_name_forum_answer);
    TextView tvPhone = (TextView) header.findViewById(R.id.tv_phone);
    TextView mTitleForumAnswer = (TextView) header.findViewById(R.id.tv_title_forum_answer);
    TextView mContentForumAnswer = (TextView) header.findViewById(R.id.tv_content_forum_answer);
    TextView mPublishTimeForumAnswer =
        (TextView) header.findViewById(R.id.tv_publishTime_forum_answer);
    TextView mForumCommentAnswer = (TextView) header.findViewById(R.id.tv_forum_comment_answer);
    ivPictureAFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureA_fourmDetail);
    ivPictureBFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureB_fourmDetail);
    ivPictureCFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureC_fourmDetail);
    ivPictureDFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureD_fourmDetail);
    ivPictureEFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureE_fourmDetail);
    ivPictureFFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureF_fourmDetail);
    tvFileForumDetail = (TextView) header.findViewById(R.id.tv_file_forumDetail);
    ivTag = (CustomTextView) header.findViewById(R.id.iv_tag);

    mNameForumAnswer.setText(mTopicPublisher);
    mTitleForumAnswer.setText(mTopicTitle);
    mContentForumAnswer.setText(mTopicdetail);
    //显示或隐藏手机号.

    if (!MyStringUtil.isEmpty(mTopicContent.getMobile())) {
      tvPhone.setVisibility(View.VISIBLE);
      tvPhone.setText(mTopicContent.getMobile());
    } else {
      tvPhone.setVisibility(View.GONE);
    }
    changeTag(mTopicContent.getLabel(), mTopicContent.getLabelName());
    // 获取头像
    String headPicturePath = mPicture;
    if (!TextUtils.isEmpty(headPicturePath)) {
      headPicturePath = FileUtil.getThumbNailFilePath(headPicturePath);
      String urlImage = ApiConst.getDownLoadUrlByGet(headPicturePath);
      ImageLoader.ImageListener listener = ImageLoader.getImageListener(mImageForumAnswer, // 控件名
          R.drawable.photo, R.drawable.photo); // 默认头像
      mImageLoader.get(urlImage, listener);
    } else {
      mImageForumAnswer.setImageResource(R.drawable.photo);
    }

    if ((TextUtils.isEmpty(mPictureA)
        && TextUtils.isEmpty(mPictureB)
        && TextUtils.isEmpty(mPictureC)
        && TextUtils.isEmpty(mPictureD)
        && TextUtils.isEmpty(mPictureE)
        && TextUtils.isEmpty(mPictureF))) {
      ivPictureAFourmDetail.setVisibility(View.GONE);
      ivPictureBFourmDetail.setVisibility(View.GONE);
      ivPictureCFourmDetail.setVisibility(View.GONE);
      ivPictureDFourmDetail.setVisibility(View.GONE);
      ivPictureEFourmDetail.setVisibility(View.GONE);
      ivPictureFFourmDetail.setVisibility(View.GONE);
    } else {
      // 获取图片A
      if (!TextUtils.isEmpty(mTopicContent.getThumbnailA())) {
        ivPictureAFourmDetail.setVisibility(View.VISIBLE);
        String urlImage = ApiConst.getDownLoadUrlByGet(mTopicContent.getThumbnailA());
        ImageLoader.ImageListener listener =
            ImageLoader.getImageListener(ivPictureAFourmDetail, // 控件名
                0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
        pics.add(mPictureA);
      } else {
        ivPictureAFourmDetail.setVisibility(View.GONE);
      }
      ivPictureAFourmDetail.setOnClickListener(this);
      // 获取图片B
      if (!TextUtils.isEmpty(mTopicContent.getThumbnailB())) {
        ivPictureBFourmDetail.setVisibility(View.VISIBLE);
        String urlImage = ApiConst.getDownLoadUrlByGet(mTopicContent.getThumbnailB());
        ImageLoader.ImageListener listener =
            ImageLoader.getImageListener(ivPictureBFourmDetail, // 控件名
                0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
        pics.add(mPictureB);
      } else {
        ivPictureBFourmDetail.setVisibility(View.GONE);
      }
      ivPictureBFourmDetail.setOnClickListener(this);

      // 获取图片C
      if (!TextUtils.isEmpty(mTopicContent.getThumbnailC(

      ))) {
        ivPictureCFourmDetail.setVisibility(View.VISIBLE);
        String urlImage = ApiConst.getDownLoadUrlByGet(mTopicContent.getThumbnailC());
        ImageLoader.ImageListener listener =
            ImageLoader.getImageListener(ivPictureCFourmDetail, // 控件名
                0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
        pics.add(mPictureC);
      } else {
        ivPictureCFourmDetail.setVisibility(View.GONE);
      }
      ivPictureCFourmDetail.setOnClickListener(this);
      // 获取图片D
      if (!TextUtils.isEmpty(mTopicContent.getThumbnailD())) {
        ivPictureDFourmDetail.setVisibility(View.VISIBLE);
        String urlImage = ApiConst.getDownLoadUrlByGet(mTopicContent.getThumbnailD());
        ImageLoader.ImageListener listener =
            ImageLoader.getImageListener(ivPictureDFourmDetail, // 控件名
                0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
        pics.add(mPictureD);
      } else {
        ivPictureDFourmDetail.setVisibility(View.GONE);
      }
      ivPictureDFourmDetail.setOnClickListener(this);
      // 获取图片E
      if (!TextUtils.isEmpty(mTopicContent.getThumbnailE())) {
        ivPictureEFourmDetail.setVisibility(View.VISIBLE);
        String urlImage = ApiConst.getDownLoadUrlByGet(mTopicContent.getThumbnailE());
        ImageLoader.ImageListener listener =
            ImageLoader.getImageListener(ivPictureEFourmDetail, // 控件名
                0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
        pics.add(mPictureE);
      } else {
        ivPictureEFourmDetail.setVisibility(View.GONE);
      }
      ivPictureEFourmDetail.setOnClickListener(this);
      // 获取图片F
      if (!TextUtils.isEmpty(mTopicContent.getThumbnailF())) {
        ivPictureFFourmDetail.setVisibility(View.VISIBLE);
        String urlImage = ApiConst.getDownLoadUrlByGet(mTopicContent.getThumbnailF());
        ImageLoader.ImageListener listener =
            ImageLoader.getImageListener(ivPictureFFourmDetail, // 控件名
                0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
        pics.add(mPictureF);
      } else {
        ivPictureFFourmDetail.setVisibility(View.GONE);
      }
      ivPictureFFourmDetail.setOnClickListener(this);
    }

    // 获取文件
    if (!TextUtils.isEmpty(mFile)) {
      tvFileForumDetail.setVisibility(View.VISIBLE);
      String file = mFile.substring(mFile.lastIndexOf("/") + 1, mFile.length());
      tvFileForumDetail.setText(file);
      tvFileForumDetail.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View view) {
          if (!TextUtils.isEmpty(mFile)) {
            ExtraDownLoadDialogFragment dialog = ExtraDownLoadDialogFragment.newInstance("", mFile);
            FragmentManager fm = getActivity().getSupportFragmentManager();
            dialog.show(fm, "");
          }
        }
      });
    }

    Date date = new Date();
    String timeDifference =
        DateUtil.dateToTimeInMillis(getActivity().getApplicationContext(), mTopicPublishTime, date);
    mPublishTimeForumAnswer.setText(timeDifference);
    mForumCommentAnswer.setText(mTopicConmmentNum);
  }

  private void changeTag(String color, String text) {
    if ((!MyStringUtil.isEmpty(color)) && (!MyStringUtil.isEmpty(text)) && (MyStringUtil.contains(
        color, "#"))) {
      ivTag.setText(text);
      ivTag.setSolidColor(Color.parseColor(color));
      ivTag.setVisibility(View.VISIBLE);
    } else {
      ivTag.setVisibility(View.GONE);
    }
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    // header不响应点击事件
    super.onListItemClick(l, v, position, id);
    if (position == 1 || position == 0) {
      return;
    }

    mTopicAnswer = mAdapter.getItem(position - 2);
    if (mTopicAnswer == null) return;
    String mAnswerId = mTopicAnswer.getRegStaffId();
    mReplyJobNo = mAnswerId;
    if ((null != mAnswerId) && mAnswerId.contains("+")) {
      String[] resultArray = mAnswerId.split("\\+");
      if (resultArray.length > 0) {
        //获取jobNO。
        mReplyJobNo = resultArray[0];
      }
    }

    mAnseerTopicId = mTopicAnswer.getId();
    LogUtil.i("mAnseerTopicId=-=-=--" + mAnseerTopicId);
    // 显示对话框.
    int[] mChoose = AgriculturalForumListFragment.SELF.equalsIgnoreCase(mFrom) ? new int[] {
        R.string.answer, R.string.lookMessage, R.string.delete, R.string.adoptReply
    } : new int[] { R.string.answer, R.string.lookMessage };
    DialogFragment mDialog = BaseSingleChoiceDialogFragment.newInstance(mChoose);
    mDialog.setTargetFragment(this, REQUEST_CHOOSE);
    FragmentManager mFm = getActivity().getSupportFragmentManager();
    mDialog.show(mFm, "");
  }

  /*取消收藏*/

  private void volleyPostCancleCollect() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MY_COLLECTION_CANCLE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("collectid", mId);//帖子id
    MyUtils.showDialogLoading(getActivity(), R.string.cancleCollect);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            ToastUtil.show("取消收藏成功");
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }
    });
  }

  /* 收藏帖子 */
  private void volleyPostCollect() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MY_COLLECTION_ADD);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("jobno", mJobNu);
    params.put("collecttypename", "");
    params.put("collecttypecode", "");
    params.put("collectid", mId);//帖子id
    MyUtils.showDialogLoading(getActivity(), R.string.collectionTopic);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          //解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {

            ToastUtil.show(R.string.success_operation);
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }
    });
  }

  /**
   * 删除前提示
   */
  private void volleyDeleteTopic() {

    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    dialog.setTitle(R.string.restart_title);
    dialog.setMessage(R.string.deleteMind);
    dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        volleyPostDelete();
      }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });

    dialog.create().show();
  }

  /**
   * 删除话题操作
   */
  protected void volleyPostDelete() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_KNOWLEDGEFORUM_POST_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mTopicId);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyResponse(String arg0) {
        Toast.makeText(getActivity(), R.string.deleteSuccess, Toast.LENGTH_SHORT).show();
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.deleteFail, Toast.LENGTH_SHORT).show();
        LogUtil.e("VolleyError==" + arg0);
      }
    });
  }

  /**
   * 分享帖子
   */
  private void volleyPostShare() {
    //String path = ApiConst.getAbsoluteUrl(ApiConst.URL_TOPIC_SHARE);
    String path = MyStringUtil.connect(ApiConst.URL_WEJIA_HOST, ApiConst.URL_TOPIC_SHARE);
    try {
      path += (URLEncoder.encode(URLEncoder.encode(mId), "utf-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    String url =
        getContext().getString(R.string.shareTopicText, getString(R.string.app_name)) + path;
    String title = getContext().getString(R.string.shareUrl);
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("text/plain");
    share.putExtra(Intent.EXTRA_SUBJECT, title);
    share.putExtra(Intent.EXTRA_TEXT, url);
    share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(Intent.createChooser(share, title));
  }

  /**
   * 响应对话框回复信息和查看资料点击事件
   */
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && (requestCode == REQUEST_TOPIC_ANSWER
        || requestCode == REQUEST_TOPIC_ANSWER_REPLY)) {
      volleyPost();
    }

    if (REQUEST_CHOOSE == requestCode && data != null) {
      // 回复信息
      int choice = data.getIntExtra(BaseSingleChoiceDialogFragment.EXTRA_RESULT, 0);
      if (choice == REQUEST_REPLY) {
        Intent replyIntent = new Intent(getActivity(), KnowledgeFroumTopicReplyActivity.class);
        replyIntent.putExtra(KnowledgeFroumTopicReplyFragment.EXTRA_ID, mId);
        replyIntent.putExtra(KnowledgeFroumTopicReplyFragment.EXTRA_VALUE, mTopicAnswer);
        replyIntent.putExtra(KnowledgeFroumTopicReplyFragment.REQUEST_TYPE,
            KnowledgeFroumTopicReplyFragment.VALUE_MESSAGE_REPLY);
        startActivityForResult(replyIntent, REQUEST_TOPIC_ANSWER_REPLY);
      }

      // 查看资料
      if (choice == REQUEST_MESSAGE) {
        Intent messageIntent = new Intent(getActivity(), KnowledgeForumPersonInfoActicity.class);
        messageIntent.putExtra(KnowledgeForumPersonInfoFragment.EXTRA_VALUE, mTopicAnswer);
        startActivity(messageIntent);
      }
      //删除回复
      if (choice == REQUEST_DELETE) {
        if (!(mJobNu.equals(mReplyJobNo))) {
          Toast.makeText(getActivity(), R.string.onlyAnswerDelete, Toast.LENGTH_SHORT).show();
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.deleteMind);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostDeleteAnswer();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });

          dialog.create().show();
        }
      }
      //采纳回复
      if (choice == REQUEST_ADOPT) {
        if (mJobNu.equals(mReplyJobNo)) {
          ToastUtil.show("只能采纳他人的答复");
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.adoptMessage);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostAdoptAnswer();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });

          dialog.create().show();
        }
      }
    }

    if (resultCode == Activity.RESULT_OK && requestCode == RESULT_EDIT) {
      //编辑成功,返回列表刷新.
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_TAG) {
      BaseParams params = (BaseParams) data.getSerializableExtra(BaseFragment.EXTRA_PARAMS);
      ZTreeNode item = (ZTreeNode) params.getItem();
      changeTag(item.getExtParam(), item.getName());
      volleypostChangeTag(item.getExtParam(), item.getName());
      mActivity.setResult(Activity.RESULT_OK);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleypostChangeTag(String label, String labelName) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_TOPIC_TAG);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mTopicId);
    params.put("label", label);
    params.put("labelName", labelName);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new SimpleResponse());
  }

  /**
   * 采纳话题回复操作
   */
  private void volleyPostAdoptAnswer() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ANSWER_ADOPT);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mAnseerTopicId);
    params.put("scoretypecode", mTopicContent.getTopicKindCode());
    params.put("scoretypename", mTopicContent.getTopicKindName());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyResponse(String arg0) {

        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {

            ToastUtil.show(R.string.success_operation);
            volleyPost();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }
    });
  }

  /**
   * 删除话题回复操作
   */
  protected void volleyPostDeleteAnswer() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_KNOWLEDGEFORUM_REPLY_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mAnseerTopicId);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyResponse(String arg0) {
        ToastUtil.show(R.string.deleteSuccess);
        MyUtils.dismissDialog();
        volleyPost();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.deleteFail);
      }
    });
  }

  @Override public void onClick(View v) {

    Intent intent = new Intent(getActivity(), PicturePagerActivity.class);
    int position = 0;
    switch (v.getId()) {
      // 图片A
      case R.id.iv_pictureA_fourmDetail:
        position = 0;
        break;

      // 图片B
      case R.id.iv_pictureB_fourmDetail:
        position = 1;
        break;

      // 图片C
      case R.id.iv_pictureC_fourmDetail:
        position = 2;
        break;

      // 图片D
      case R.id.iv_pictureD_fourmDetail:
        position = 3;
        break;

      // 图片E
      case R.id.iv_pictureE_fourmDetail:
        position = 4;
        break;

      // 图片D
      case R.id.iv_pictureF_fourmDetail:
        position = 5;
        break;

      default:
        break;
    }
    intent.putStringArrayListExtra(PicturePagerFragment.EXTRA_PICS, pics);
    intent.putExtra(PicturePagerFragment.EXTRA_POSITION, position);
    startActivity(intent);
  }

  @Override public void initMockData() {
    super.initMockData();
    //(MyStringUtil.equals(mCurrentUser.getJobNumber(),
    //    mTopicContent.getRemindJobNo())) {
    mTopicContent.setRemindJobNo(mCurrentUser.getJobNumber());
  }
}
